package com.xy.job.executor.core.server

import com.xy.job.core.api.request.JobKillParam
import com.xy.job.core.api.request.JobLogParam
import com.xy.job.core.api.request.JobTriggerParam
import com.xy.job.executor.core.client.IAdminClient
import com.xy.job.executor.core.job.*
import kotlinx.coroutines.async
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

class ExecutorServiceBiz(
    private val adminClient: IAdminClient,
) {

    fun trigger(param: JobTriggerParam): Boolean {
        val scriptType = param.scriptType
        val jobHandlerName: String = param.jobHandlerName.takeIf { scriptType == null }
            ?: ScriptJobHandler::class.simpleName!!

        val jobContext = JobContext(
            jobId = param.jobId,
            jobInstanceId = param.jobInstanceId,
            jobName = param.jobName,
            jobHandlerName = jobHandlerName,
            executeParams = param.executeParams,
            timeout = param.timeout,
            dataTime = param.dataTime,
            scriptType = scriptType,
            scriptSource = param.scriptSource,
        )
        val job = Job(
            jobContext = jobContext,
            adminClient = adminClient,
        )
        ExecutorCoroutineScope.launch {
            val coroutineJob = async { job.execute() }
            JobRegistry.register(param.jobInstanceId, coroutineJob)
        }
        return true
    }

    fun kill(param: JobKillParam): Boolean {
        val coroutineJob = JobRegistry.remove(param.jobInstanceId)
        coroutineJob?.cancel("job is killed")
        return true
    }

    fun log(param: JobLogParam) {
        TODO("Not yet implemented")
    }
}